<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="选择加工单"
    style="min-width: 1200px"
    draggable
    @close="closeDialog"
  >
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="changePlant"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            :disabled="searchParam.plantId === ''"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in workshopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划批次">
          <el-input
            v-model="searchParam.planBatch"
            placeholder="请输入计划批次"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="searchParam.planDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            @change="getplanDate"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <div class="formTable">
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          :key="Math.random"
          max-height="400"
          highlight-current-row
          @current-change="handleCurrentChange1"
          border
        >
          <el-table-column
            label="工厂"
            prop="plantCode"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column
            label="工作中心"
            prop="workCenterName"
            min-width="180"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.workCenterCode }}-{{ scope.row.workCenterName }}
            </template>
          </el-table-column>
          <el-table-column
            label="工作年"
            prop="planYear"
            min-width="100"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope"> {{ scope.row.planYear }}年 </template>
          </el-table-column>
          <el-table-column
            label="工作周"
            prop="planWeek"
            min-width="100"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope"> {{ scope.row.planWeek }}周 </template>
          </el-table-column>
          <el-table-column
            label="加工单号"
            prop="workOrderCode
"
            min-width="180"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.workOrderCode }}
            </template>
          </el-table-column>
          <el-table-column
            label="计划批次"
            prop="planBatch"
            min-width="100"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="计划日期"
            prop="planDate"
            value-format="YYYY-MM-DD"
            min-width="100"
            show-overflow-tooltip
            :formatter="formatDate"
            align="center"
          />
          <el-table-column
            label="班次顺序"
            prop="shiftName"
            min-width="100"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="存货编码-名称"
            prop="materialCode"
            min-width="180"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.materialCode }}
              {{ scope.row.materialCode && scope.row.materialName ? "-" : "" }}
              {{ scope.row.materialName }}
            </template>
          </el-table-column>
          <el-table-column
            label="计划数量"
            prop="planQuantity"
            min-width="100"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.planQuantity ? scope.row.planQuantity : 0 }}
            </template>
          </el-table-column>
          <el-table-column
            label="总完成数量"
            prop="planFinishQuantity"
            min-width="100"
            show-overflow-tooltip
            align="center"
          />

          <!-- <el-table-column
            label="已完成数量"
            prop="planFinishQuantity"
            min-width="100"
            show-overflow-tooltip
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="数量单位"
            prop="quantityUnit"
            min-width="100"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ useDictionary("MeasurementUnit", scope.row.quantityUnit) }}
            </template>
          </el-table-column> -->
        </el-table>
        <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElMessage, ElForm } from "element-plus";
import { ref, reactive, watch, onBeforeUnmount } from "vue";
import request from "@/utils/request";
defineOptions({
  name: "MESWORKORDEREQUIPPLAN",
  inheritAttrs: false,
});

const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  brekList: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const multipleTable = ref();
const getBreakList = () => {
  //定义了一个空数组
  let checkedrow: any = [];
  //循环列表所有的数据
  tableData.value.forEach((item) => {
    //循环后台返回需要打钩的数据
    props.brekList.forEach((v) => {
      //这就是个条件  根据自己的条件去写
      if (item.id == v.mesWorkOrderPlanId) {
        console.log(item);

        //给空数组里面添加我需要回显打钩的数据
        checkedrow.push(item); // 相等添加到空数组中
      }
    });
  });
  //最主要的就是这个方法这个方法在dom渲染完会去回调
  nextTick(() => {
    //遍历回显数组
    checkedrow.forEach((row) => {
      console.log(111111);

      //singleTableRef这个是在table上面加的ref的值  通过它的属性方法去看那几个属性打钩
      multipleTable.value.toggleRowSelection(row, true); // 回显
    });
  });

  console.log(999);

  // tableData.value.forEach((item: any) => {
  //   if (item.id === props.brekList[0].mesWorkOrderPlanId) {
  //     multipleTable.value.toggleRowSelection(item, true);
  //   }
  // });
};

//获取表格数据 api 方法
const requestApi = "/mes/mesworkorderplan/queryByPage";
//获取数据初始化参数
const initParam = {};
// 初始化搜索参数数据
// 初始化搜索参数数据
const searchParamInit = {
  planDateSearch: [],
  planDateStart: "",
  planDateEnd: "",
  planBatch: "",
  orderState: "",
  plantId: "",
  workCenterId: "",
};
// 是否需要分页
const pagination = true;
// 无需二次数据处理&不传赞数也行
const dataCallBack = (data: any, parentIndex = "") => {
  // data.forEach((item: any, index: number) => {
  //   const currentIndex =
  //     parentIndex === ""
  //       ? (index + 1).toString()
  //       : `${parentIndex}.${index + 1}`;
  //   item.parentIndex = currentIndex;
  //   if (item.children && item.children.length > 0) {
  //     dataCallBack(item.children, currentIndex);
  //   }
  // });
  return data;
};

// 数据请求错误后处理
function requestError() {}
//删除
const deleteParam = {
  api: "",
  data: {},
};

const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getTableList();
    if (props.brekList.length > 0) {
      console.log(4444);

      // getBreakList();
    }
  }
);

// 选择高亮
const currentRow = ref();
const handleCurrentChange1 = (val: any) => {
  currentRow.value = val;
};

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  handelRest();
}

const handelRest = () => {
  searchParam.value.planDateStart = "";
  searchParam.value.planDateSearch = [];
  searchParam.value.planDateEnd = "";
  searchParam.value.workCenterId = "";
  searchParam.value.planBatch = "";
  workshopList.value = [];
  searchParam.value.plantId = "";
  // search();
};

/** email消息发送记录保存提交 */
function handleSubmit() {
  if (currentRow.value) {
    emit("change-visible", false, currentRow.value);
  } else {
    return ElMessage.warning("请选择工作任务");
  }
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

///工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const changePlant = (e) => {
  if (e) {
    getWorkshopList(e);
  } else {
    searchParam.value.planDateStart = "";
    searchParam.value.planDateEnd = "";
    searchParam.value.workCenterId = "";
    searchParam.value.planBatch = "";
    workshopList.value = [];
  }
};
//工作中心
const workshopList = ref([]);
const getWorkshopList = async (plantId: String) => {
  const { data } = await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: { plantId: plantId },
  });
  workshopList.value = data;
};

function getplanDate(data: any) {
  if (data) {
    searchParam.value.planDateSearch = data;
    searchParam.value.planDateStart = data[0];
    searchParam.value.planDateEnd = data[1];
  } else {
    searchParam.value.planDateSearch = [];
    searchParam.value.planDateStart = "";
    searchParam.value.planDateEnd = "";
  }
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
onMounted(() => {
  getTableList();
  getPlantList();
});
</script>

<style scoped lang="scss">
:deep(.el-table th .cell) {
  color: black;
  font-weight: 700;
}
.progress {
  color: red;
}
.success {
  color: rgb(100, 207, 86);
}
</style>
